package com.example.test622.detail

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import com.example.net.entity.CommentEntity
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class RecomonViewModel:BaseViewModel<RecommonIntent,RecommonState>() {
	init {
		viewModelScope.launch {
			intent.consumeAsFlow().collect{
				when(it){
					is RecommonIntent.getRecommonVideo->loadRecommon(it.page,it.size)
					is RecommonIntent.getComment->loadComment(it.type,it.id)
					is RecommonIntent.putComment->putC(it.commentEntity)
					is RecommonIntent.getDanmu->loadDanmu(it.type,it.item)
				}
			}
		}
	}
	
	private suspend fun loadDanmu(type: Int, item: String) {
		val s = try {
			val res = service.getDanmu(type,item)
			if(res.code == 0){
				RecommonState.DanmuSuccess(res)
			}else{
				RecommonState.RecommonFail(res.msg)
			}
		}catch (e:Exception){
			RecommonState.RecommonFail(e.message?:"")
		}
		state.postValue(s)
	}
	
	private suspend fun putC(commentEntity: CommentEntity) {
		val s = try {
			val res = service.putComment(commentEntity)
			if(res.code == 0){
				RecommonState.putComment(res)
			}else{
				RecommonState.RecommonFail(res.msg)
			}
		}catch (e:Exception){
			RecommonState.RecommonFail(e.message?:"")
		}
		state.postValue(s)
	}
	
	private suspend fun loadComment(type: Int, id: String) {
		val s = try {
			val res = service.getComment(type,id)
			if(res.code == 0){
				RecommonState.CommentSuccess(res)
			}else{
				RecommonState.RecommonFail(res.msg)
			}
		}catch (e:Exception){
			RecommonState.RecommonFail(e.message?:"")
		}
		state.postValue(s)
	}
	
	private suspend fun loadRecommon(page: Int, size: Int) {
			val s = try {
				val res = service.getRecommendMutilVideo(page, size)
				if(res.code == 0){
					RecommonState.RecommonSuccess(res)
				}else{
					RecommonState.RecommonFail(res.msg)
				}
			}catch (e:Exception){
				RecommonState.RecommonFail(e.message?:"")
			}
		state.postValue(s)
	}
}